package com.anjie.powerproject.service.impl;

import com.anjie.powerproject.common.MockDataUtil;
import com.anjie.powerproject.entity.GraphInfo;
import com.anjie.powerproject.entity.PreStrategy;
import com.anjie.powerproject.entity.StrategyOutput;
import com.anjie.powerproject.map.StrategyMap;
import com.anjie.powerproject.pojo.dto.CompareQueryDTO;
import com.anjie.powerproject.pojo.dto.StrategyCompareDTO;
import com.anjie.powerproject.pojo.dto.StrategyCompareQueryDTO;
import com.anjie.powerproject.service.GraphInfoService;
import com.anjie.powerproject.service.PreStrategyService;
import com.anjie.powerproject.service.StrategyDisplayService;
import com.anjie.powerproject.service.StrategyOutputService;
import com.anjie.powerproject.util.DateRange;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class StrategyDisplayServiceImpl implements StrategyDisplayService {
    private static final Logger logger = LoggerFactory.getLogger(StrategyDisplayServiceImpl.class);

    @Autowired
    PreStrategyService preStrategyService;

    @Autowired
    StrategyOutputService strategyOutputService;

    @Autowired
    StrategyMap strategyMap;

    @Autowired
    GraphInfoService graphInfoService;

    @Override
    public StrategyCompareDTO compare(StrategyCompareQueryDTO query) throws ParseException {
        checkCompareParams(query);

        StrategyCompareDTO compareDTO = new StrategyCompareDTO();

        List<GraphInfo> graphInfoList=graphInfoService.getAllGraphInfo();
        Collections.sort(graphInfoList,new Comparator<GraphInfo>() {
            @Override
            //按照图谱开始时间从小到大排序
            public int compare(GraphInfo b1, GraphInfo b2) {
                return b1.getGraphStartTime().compareTo(b2.getGraphStartTime());
            }
        });

        // 生成日期列表
        List<String> dateList = DateRange.getDateListOfDateRange(query.getStartTime(), query.getEndTime());
        compareDTO.setDateList(dateList);

        int flag=-1;

        List<String> timePoints=new ArrayList<>();  //存放时间节点，更换图谱时把节点存入
        List<Integer> strategyTypeList=new ArrayList<>(); //存放每段时间对应的策略
        String preDate=dateList.get(0);
        /**
         * 根据各个图谱的时间段，将整个时间段分割
         */
        for(String s:dateList){
            String MMDD=s.substring(5);
//          int ans=s1.compareTo(s2)  s1=s2 ans=0; s1>s2 ans=1; s1<s2 ans=-1;
            if(MMDD.compareTo(graphInfoList.get(0).getGraphStartTime())>=0  //月日在春季图谱运行期间， 春季图谱对应flag=0
                    &&MMDD.compareTo(graphInfoList.get(0).getGraphEndTime())<=0){
                if(flag!=0){  //遇上一次的flag不一样，表示更换图谱了，添加时间节点
                    flag=0;
                    timePoints.add(preDate);
                    timePoints.add(s);
                    strategyTypeList.add(graphInfoList.get(0).getStrategyType());
                }
            }else if(MMDD.compareTo(graphInfoList.get(1).getGraphStartTime())>=0  //月日在夏季图谱运行期间  夏季图谱对应flag=1
                    &&MMDD.compareTo(graphInfoList.get(1).getGraphEndTime())<=0){
                if(flag!=1){
                    flag=1;
                    timePoints.add(preDate);
                    timePoints.add(s);
                    strategyTypeList.add(graphInfoList.get(1).getStrategyType());
                }
            }else if(MMDD.compareTo(graphInfoList.get(2).getGraphStartTime())>=0  //月日在秋季图谱运行期间  秋季图谱对应flag=2
                    &&MMDD.compareTo(graphInfoList.get(2).getGraphEndTime())<=0){
                if(flag!=2){
                    flag=2;
                    timePoints.add(preDate);
                    timePoints.add(s);
                    strategyTypeList.add(graphInfoList.get(2).getStrategyType());
                }
            }else{   //冬季图谱
                if(flag!=3){
                    flag=3;
                    timePoints.add(preDate);
                    timePoints.add(s);
                    strategyTypeList.add(graphInfoList.get(3).getStrategyType());
                }
            }
            preDate=s;
        }
        String lastTime=dateList.get(dateList.size()-1);
        if(!lastTime.equals(timePoints.get(timePoints.size()-1))){
            timePoints.add(lastTime); //添加最后一个时间节点
        }
        timePoints.remove(0);
//        for(int i=0;i<timePoints.size();i++)
//            System.out.println(timePoints.get(i));
//
//        for(int i=0;i<strategyTypeList.size();i++)
//            System.out.println(strategyTypeList.get(i));

        int strategyListSize=strategyTypeList.size()-1;
        for(int i=strategyListSize;i>0;i--){
            if(strategyTypeList.get(i).compareTo(strategyTypeList.get(i-1))==0){ //策略一致
                timePoints.remove(i*2);
                timePoints.remove(i*2-1);
                strategyTypeList.remove(i);
            }
        }
//        System.out.println("----------------");

        List<List<PreStrategy>> sourceList=new ArrayList<>();
        List<List<PreStrategy>> targetList=new ArrayList<>();
        List<List<StrategyOutput>> historyList=new ArrayList<>();
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
        //根据分好的时间段来查数据
        for(int i=0;i<strategyTypeList.size();i++){
//            System.out.println(query.getSourceModelId()+"  "+query.getSourceModelId()+"  "+strategyTypeList.get(i)+"  "+timePoints.get(i*2)+"  "+timePoints.get(i*2+1));
//            strategyTypeList.get(i)+"  "+timePoints.get(i*2)+"  "+timePoints.get(i*2+1) 为一组，策略  开始时间  结束时间
            sourceList.addAll(preStrategyService.getPreStrategyByCodeAndDateRange(1, query.getSourceModelId(), sf.parse(timePoints.get(i*2)), sf.parse(timePoints.get(i*2+1)), strategyTypeList.get(i)));
            targetList.addAll(preStrategyService.getPreStrategyByCodeAndDateRange(1, query.getTargetModelId(), sf.parse(timePoints.get(i*2)), sf.parse(timePoints.get(i*2+1)), strategyTypeList.get(i)));
            historyList.addAll(strategyOutputService.getStrategyOutputByCodeAndDateRange(1, sf.parse(timePoints.get(i*2)), sf.parse(timePoints.get(i*2+1)), strategyTypeList.get(i)));
        }
        compareDTO.setSourceList(strategyMap.toDTOList(sourceList));
        compareDTO.setTargetList(strategyMap.toDTOList(targetList));
        compareDTO.setHistoryList(strategyMap.toDTO2List(historyList));

        // 工况
//        List<List<PreStrategy>> sourceList = preStrategyService.getPreStrategyByCodeAndDateRange(1, query.getSourceModel(), query.getStartTime(), query.getEndTime(), query.getSourceModelStrategyType());
//        compareDTO.setSourceList(strategyMap.toDTOList(sourceList));
//
//        List<List<PreStrategy>> targetList = preStrategyService.getPreStrategyByCodeAndDateRange(1, query.getTargetModel(), query.getStartTime(), query.getEndTime(), query.getTargetModelStrategyType());
//        compareDTO.setTargetList(strategyMap.toDTOList(targetList));

        // 历史工况
//        List<List<StrategyOutput>> historyList = strategyOutputService.getStrategyOutputByCodeAndDateRange(1, query.getStartTime(), query.getEndTime());
//        compareDTO.setHistoryList(strategyMap.toDTO2List(historyList));

//        System.out.println("getSourceList: "+compareDTO.getSourceList());
//        System.out.println("getHistoryList: "+compareDTO.getHistoryList());
//        System.out.println("getTargetList: "+compareDTO.getTargetList());
        return compareDTO;
    }

    private void checkCompareParams(StrategyCompareQueryDTO queryDTO) {
        Date startTime = queryDTO.getStartTime();
        Date endTime = queryDTO.getEndTime();
        //如果有一个为空，则
        if (startTime == null || endTime == null) {
            logger.error("输入时间有空值，不合法");
            throw new RuntimeException("输入时间有空值，不合法");
        }
        //如果开始时间大于结束时间，
        if (startTime.compareTo(endTime) > 0) {
            logger.error("开始时间大于结束时间，输入不合法");
            throw new RuntimeException("开始时间大于结束时间，输入不合法");
        }
    }
}
